﻿using GalaSoft.MvvmLight.Messaging;
using gAMS_Sacombank.AssetService;
using gAMS_Sacombank.CommonClass;
using gAMS_Sacombank.Resources;
using gAMS_Sacombank.ViewModels.Common;
using mvvmCommon;
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace gAMS_Sacombank.ViewModels.AssCommon
{
    public class AssetTypeEditViewModel:ViewModelBase
    {
         private ASSET_TYPEClient asset_typeClient;

         public AssetTypeEditViewModel()
        {
            this.actionCommand = new ActionButton(this);
            this.messagePop = new MessageAlarmViewModel();            
            Messenger.Default.Register<ChildMessage>(this, CurrencyEditSendMessageRecieve);

            this.Load();
        }

        private void CurrencyEditSendMessageRecieve(ChildMessage obj)
        {

            if (obj.action.Equals(ActionMenuButton.View))
            {
                ActionMenuButton.actionControl.SetAllAction(null, null, null, null, null, null, actionCommand);
                this.HeaderText = CommonResource.lblApprove;
                this.IsView = false;
            }
            else
            {
                ActionMenuButton.actionControl.SetAllAction(null, actionCommand, null, null, null);
                this.isEdit = obj.isEdit;
                this.HeaderText = this.isEdit ? CommonResource.lblEdit : CommonResource.lblInsert;
                this.IsView = true;
            }

            this.messagePop.Reset();
            this.CurrentItem = obj.currentObject != null ? (obj.currentObject as ASS_TYPE)
                : new ASS_TYPE()
                {
                    MAKER_ID = CurrentSystemLogin.CurrentUser.TLNANME,
                    TYPE_ID = "",
                    TYPE_CODE="",
                    TYPE_NAME = "",
                   
                    NOTES = "",
                    RECORD_STATUS = "1",
                    AUTH_STATUS = "U"
                };
            this.IsChecked = this.currentItem.RECORD_STATUS.Equals("1") ? "True" : "False";
            if (this.currentItem.AUTH_STATUS.Equals('A'))
                this.IsApproved = Visibility.Visible.ToString();
            else
                this.IsApproved = Visibility.Collapsed.ToString();

            this.OnPropertyChanged("IsView");
            this.OnPropertyChanged("IsChecked");
            this.OnPropertyChanged("IsApproved");
            this.OnPropertyChanged("");
        }        

        #region[All Properties]

        public bool IsView { get; set; }

        public string IsApproved { get; set; }

        public string IsChecked { get; set; }
        
        //Message Alarm validate
        private MessageAlarmViewModel messagePop;
        public MessageAlarmViewModel MessagePop
        {
            get
            {
                return this.messagePop;
            }

            set
            {
                this.messagePop = value;
                this.OnPropertyChanged("MessagePop");
            }
        }
        // function insert or edit
        private bool isEdit;
        public string IsEnable
        {
            get
            {
                return (!this.isEdit).ToString();
            }
        }

        //Action Button Property    
        private ICommand actionCommand;
        public ICommand ActionCommand
        {
            get
            {
                return this.actionCommand;
            }

            set 
            {
                this.actionCommand = value;
                this.OnPropertyChanged("ActionCommand");
            }
        }

        //Current Items edit
        private ASS_TYPE currentItem;
        public ASS_TYPE CurrentItem
        {
            get
            {
                return this.currentItem;
            }

            set
            {
                this.currentItem = value;
                this.OnPropertyChanged("CurrentItem");
            }
        }                

        //set header title
        private string headerText;
        public string HeaderText
        {
            get
            {
                return this.headerText;
            }

            set
            {
                this.headerText = value;
                this.OnPropertyChanged("HeaderText");
            }
        }

 
        #endregion

        #region[Action Functions]

        private void OkAction()
        {
            RefreshValidator();
            if (!this.messagePop.HasError())
            {
                this.currentItem.RECORD_STATUS = this.IsChecked.Equals("True") ? "1" : "0";
                if (this.isEdit)
                {
                    MyHelper.IsBusy();
                    this.asset_typeClient.UpdateAsset_TypeAsync(this.currentItem);
                }
                else
                {
                    MyHelper.IsBusy();
                    this.currentItem.CREATE_DT = DateTime.Now;
                    this.asset_typeClient.InsertAsset_TypeAsync(this.currentItem);
                }
            }
        }

        private void CancelAction()
        {            
            Messenger.Default.Send(new ParentMessage() { currentObject = null });
        }

        private void Approve()
        {
            this.messagePop.Reset();
            if (this.currentItem.AUTH_STATUS.Equals("A")) return;
            if (this.currentItem.MAKER_ID.Equals(CurrentSystemLogin.CurrentUser.TLNANME))
            {
                this.messagePop.SetSingleError(ValidatorResource.lblErrorPermission);
                return;
            }
            this.currentItem.CHECKER_ID = CurrentSystemLogin.CurrentUser.TLNANME;
            this.currentItem.APPROVE_DT = DateTime.Now;
            MyHelper.IsBusy();
            this.asset_typeClient.ApproveAsset_TypeAsync(this.currentItem);
        }

        private void RefreshValidator()
        {
            this.messagePop.Reset();
            string notEmpty = " " + ValidatorResource.NotEmpty;

            //if (this.currentItem.Unit_Id == null || this.currentItem.Unit_Id.Equals(""))
            //    this.messagePop.SetError(AssetResource.Unit_Id + notEmpty);
            if (this.currentItem.TYPE_NAME.Equals(""))
                this.messagePop.SetError(AssCommonResource.Type_Name + notEmpty);
        }

        private void Load()
        {
            try
            {
                this.asset_typeClient = new ASSET_TYPEClient();

                this.asset_typeClient.UpdateAsset_TypeCompleted += new EventHandler<UpdateAsset_TypeCompletedEventArgs>(updateCompleted);
                this.asset_typeClient.InsertAsset_TypeCompleted += new EventHandler<InsertAsset_TypeCompletedEventArgs>(insetCompleted);
                this.asset_typeClient.ApproveAsset_TypeCompleted += new EventHandler<ApproveAsset_TypeCompletedEventArgs>(approveCompleted);
            }
            catch (Exception)
            {
                this.messagePop.SetSingleError(CommonResource.errorCannotConnectServer);
            }
        }

        private void updateCompleted(object sender, UpdateAsset_TypeCompletedEventArgs e)
        {
            try
            {
                if (e.Result.Equals(ListMessage.True))
                {
                    this.IsApproved = Visibility.Collapsed.ToString();
                    this.OnPropertyChanged("IsApproved");
                    this.messagePop.Successful(ValidatorResource.UpdateSuccessful);
                }
                else
                {
                    //this..AUTH_STATUS = this.preAuthStatus;
                    if (ListMessage.Message.ContainsKey(e.Result))
                        this.messagePop.SetSingleError(ValidatorResource.ErrorUpdate + "\n " + ListMessage.Message[e.Result]);
                    else
                        this.messagePop.SetSingleError(ValidatorResource.ErrorUpdate + "\n " + e.Result);
                }
            }
            catch (Exception)
            {
                this.messagePop.SetSingleError(CommonResource.errorCannotConnectServer);
            }
            finally
            {
                MyHelper.IsFree();
            }
        }

        private void insetCompleted(object sender, InsertAsset_TypeCompletedEventArgs e)
        {
            try
            {
                if (e.Result!=null)
                {
                    this.CurrentItem.TYPE_ID = e.Result;
                    this.messagePop.Successful(ValidatorResource.InsertSuccessful);
                    Messenger.Default.Send(new ParentMessage() { isEdit = this.isEdit, currentObject = this.currentItem });
                }
                else
                {
                    if (ListMessage.Message.ContainsKey(e.Result))
                        this.messagePop.SetSingleError(ValidatorResource.ErrorInsert + "\n " + ListMessage.Message[e.Result]);
                    else
                        this.messagePop.SetSingleError(ValidatorResource.ErrorInsert + "\n " );
                }
            }
            catch (Exception)
            {
                this.messagePop.SetSingleError(CommonResource.errorCannotConnectServer);
            }
            finally
            {
                MyHelper.IsFree();
            }
        }

        private void approveCompleted(object sender, ApproveAsset_TypeCompletedEventArgs e)
        {
            try
            {
                if (e.Result.Equals(ListMessage.True))
                {
                    this.currentItem.AUTH_STATUS = "A";
                    this.IsApproved = Visibility.Visible.ToString();
                    this.OnPropertyChanged("IsApproved");
                    this.messagePop.Successful(ValidatorResource.SuccessfulApprove);
                }
                else
                {
                    if (ListMessage.Message.ContainsKey(e.Result))
                        this.messagePop.SetSingleError(ValidatorResource.ErrorApprove + "\n " + ListMessage.Message[e.Result]);
                    else
                        this.messagePop.SetSingleError(ValidatorResource.ErrorApprove + "\n " + e.Result);
                }
            }
            catch (Exception)
            {
                this.messagePop.SetSingleError(CommonResource.errorCannotConnectServer);
            }
            finally
            {
                MyHelper.IsFree();
            }
        }

        #endregion

        //Command button action
        public class ActionButton : ICommand
        {

            private AssetTypeEditViewModel viewModel;
            public ActionButton(AssetTypeEditViewModel viewModel)
            {
                this.viewModel = viewModel;
                this.viewModel.PropertyChanged += (s, e) =>
                {
                    if (this.CanExecuteChanged != null)
                    {
                        this.CanExecuteChanged(this, new EventArgs());
                    }
                };
            }

            public bool CanExecute(object parameter)
            {
                return true;
            }

            public event EventHandler CanExecuteChanged;

            public void Execute(object parameter)
            {
                switch (parameter.ToString())
                {
                    case "Cancel": this.viewModel.CancelAction(); break;
                    case ActionMenuButton.Update: this.viewModel.OkAction(); break;
                    case ActionMenuButton.Approve: this.viewModel.Approve(); break;                    
                    default: break;
                }

            }
        }
    }
}
